package com.handpay.zztong.hp.qualification.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.HttpSFTConnector;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.notice.ApiNoticeFactory;
import com.handpay.framework.notice.ApiNoticeListener;
import com.handpay.framework.utils.BitmapLoader;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.MyAsyncTask;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.accountcenter.widget.ConfirmPhotoView;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.HttpUrlConstant;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.protocol.UploadProtocolConstant;
import com.handpay.zztong.hp.qualification.model.IDCardStatus;
import com.handpay.zztong.hp.qualification.model.IDCardStatusModel;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.Hashtable;
import java.util.List;
import java.util.zip.CRC32;

import se.krka.kahlua.vm.LuaTable;

import static com.handpay.zztong.hp.permission.PermissionRequestCode.REQUEST_CODE_PERMISSION_CAMERA;

/***
 * 身份证补齐
 */
public class IDCardateActivity extends ZZTongActivity {
    //图片转态指示器
    private ImageView img_uploadcard_stuts;
    //上中下布局
    private LinearLayout reupload_warning, linear_tip_detail, linear_card;
    //提示文本
    private TextView tv_failDes0;
    private TextView tv_failDes;

    private TextView tv_tip_of_card;
    private TextView tv_tip_of_card_name;
    private TextView tv_tip_of_card_number;
    //身份证照片前后以及手持照片
    private ConfirmPhotoView c_id_front_photo, c_person_with_id, c_id_back_photo;
    private Button btn_upload_cardpic;
    private IDCardStatus cardStatus;

    private Uri mPicUri;
    private int TAKE_PICTURE = 1;
    private int TAKE_PICTURE_FRONT = TAKE_PICTURE + 1;
    private int TAKE_PICTURE_BLACK = TAKE_PICTURE + 2;
    private int TAKE_PICTURE_IN_HAND = TAKE_PICTURE + 3;
    private String frontUri;
    private volatile boolean mFrontUploaded = false;
    private String backUri;
    private volatile boolean mBackUploaded = false;
    private String inHandUri;
    private volatile boolean mInHandUploaded = false;

    private IDCardStatusModel cardStatusModel;
    private MyAsyncTask<Void, UploadProtocolConstant.TYPE, Integer> mTask;

    @Override
    protected boolean isShownTopBar() {
        return true;
    }

    @Override
    public com.handpay.zztong.hp.bean.ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.card_reset_upload), true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_idcardate);
        super.onCreate(savedInstanceState);
        cardStatusModel = new IDCardStatusModel();
        initPermission();
        getSupplyData();
        initView();
    }

    private void initView() {
        reupload_warning = (LinearLayout) findViewById(R.id.reupload_warning);
        img_uploadcard_stuts = (ImageView) findViewById(R.id.img_uploadcard_stuts);
        tv_failDes = (TextView) findViewById(R.id.tv_failDes);
        linear_tip_detail = (LinearLayout) findViewById(R.id.linear_tip_detail);
        tv_tip_of_card = (TextView) findViewById(R.id.tv_tip_of_card);
        tv_tip_of_card_name = (TextView) findViewById(R.id.tv_tip_of_card_name);
        tv_tip_of_card_number = (TextView) findViewById(R.id.tv_tip_of_card_number);
        linear_card = (LinearLayout) findViewById(R.id.linear_card);
        c_id_front_photo = (ConfirmPhotoView) findViewById(R.id.c_id_front_photo);
        c_id_back_photo = (ConfirmPhotoView) findViewById(R.id.c_id_back_photo);
        c_person_with_id = (ConfirmPhotoView) findViewById(R.id.c_person_with_id);
        btn_upload_cardpic = (Button) findViewById(R.id.btn_upload_cardpic);
        btn_upload_cardpic.setOnClickListener(this);
        tv_failDes0 = (TextView) findViewById(R.id.tv_failDes0);
    }

    private void refreshView() {
        if (cardStatus != null) {
            if (!TextUtils.isEmpty(cardStatus.getStatus())) {
                if (cardStatus.getStatus().equals(IDCardStatus.STATIC_STATUC_WAITE)) {//等待上传  提示信息都不显示
                    reupload_warning.setVisibility(View.GONE);
                    linear_tip_detail.setVisibility(View.VISIBLE);
                } else {
                    reupload_warning.setVisibility(View.VISIBLE);
                    if (cardStatus.getStatus().equals(IDCardStatus.STATIC_STATUC_FAIL)) {//审核失败显示红色提示信息
                        reupload_warning.setBackgroundResource(R.drawable.input_msg_bg);
                        img_uploadcard_stuts.setBackgroundResource(R.drawable.warn);
                        tv_failDes0.setVisibility(View.VISIBLE);
                        tv_failDes.setText(getString(R.string.checkfailreason1) + cardStatus.getAuditInfo());
                    } else if (cardStatus.getStatus().equals(IDCardStatus.STATIC_STATUC_SUCCESS)) {//审核成功
                        reupload_warning.setBackgroundResource(R.drawable.input_msg_sucess_bg);
                        img_uploadcard_stuts.setBackgroundResource(R.drawable.success);
                        tv_failDes.setTextColor(Color.rgb(27, 247, 46));
                        tv_failDes.setText(getString(R.string.idcard_verification_success));
                        linear_tip_detail.setVisibility(View.GONE);
                        btn_upload_cardpic.setVisibility(View.GONE);
                    } else {//审核中--框框样式改变  左边icon隐藏urce(R.drawable.input_msg_ing_bg);
                        img_uploadcard_stuts.setVisibility(View.GONE);
                        tv_failDes.setTextColor(Color.rgb(252, 190, 67));
                        tv_failDes.setText(getString(R.string.idcard_verification_ing));
                        btn_upload_cardpic.setVisibility(View.GONE);
                    }
                }
            }
            //"http://10.48.171.115:8080/hpayAcolyte-webapp/service/ShowEncryptoImage?pkValue=HXZZT@fplei05_patch_0&absolutelyFilePath=/mnt/mfs/static/hpay/risk/image/patch/HXZZT/20160825/fplei05_0_20160825151353=02=01.jpeg"
            //设置姓名，身份证值
            tv_tip_of_card_name.setText(cardStatus.getName());
            tv_tip_of_card_number.setText(CommonUtils.formattingCertNo4_2(cardStatus.getCertNo()));
            //这里传一个总的审核状态  没有 默认值为 01 待补件
            c_id_front_photo.init(TextUtils.isEmpty(cardStatus.getStatus()) ? 1 : Integer.parseInt(cardStatus.getStatus()), getString(R.string.ID_card_photo), R.drawable.idcardphoto, R.drawable.idcardphoto_large, cardStatus.getFrontCCPic(), cardStatus.getFrontCCPicStatus(), mUploadClickListener);
            c_id_back_photo.init(TextUtils.isEmpty(cardStatus.getStatus()) ? 1 : Integer.parseInt(cardStatus.getStatus()), getString(R.string.ID_card_back_photo), R.drawable.idcardbackphoto, R.drawable.idcardbackphoto_large, cardStatus.getBackCCPic(), cardStatus.getBackCCPicStatus(), mUploadClickListener);
            c_person_with_id.init(TextUtils.isEmpty(cardStatus.getStatus()) ? 1 : Integer.parseInt(cardStatus.getStatus()), getString(R.string.ID_person_with_card), R.drawable.withidcardphoto, R.drawable.withidcardphoto_large, cardStatus.getHoldPic(), cardStatus.getHoldPicStatus(), mUploadClickListener);
        }
    }

    /**
     * 获取过期补件信息
     */
    private void getSupplyData() {
        cardStatus = new IDCardStatus();
        Hashtable<String, String> params = new Hashtable<>();
        params.put("account", SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put("channel", ClientEngine.CHANNEL);
//        this.doJsonPost(true, this, HttpUrlConstant.Do_tGetSupplyAuditInfo, IDCardStatus.class, params, true);
        cardStatusModel.doSupplyData(this, params, new BusinessEngineListener<IDCardStatus>() {
            @Override
            public void callbackBusinessResponse(IDCardStatus idCardStatus) {
                cardStatus = idCardStatus;
                String auditInfo = cardStatus.getAuditInfo();
                if (!TextUtils.isEmpty(auditInfo)) cardStatus.setAuditInfo(SecureManager.getInstance().des(auditInfo, 0, null));
                String name = cardStatus.getName();
                if (!TextUtils.isEmpty(name)) cardStatus.setName(SecureManager.getInstance().des(name, 0, null));
                String certNo = cardStatus.getCertNo();
                if (!TextUtils.isEmpty(certNo)) cardStatus.setCertNo(SecureManager.getInstance().des(certNo, 0, null));
                String frontCCPic = cardStatus.getFrontCCPic();
                if (!TextUtils.isEmpty(frontCCPic)) cardStatus.setFrontCCPic(frontCCPic);
                String backCCPic = cardStatus.getBackCCPic();
                if (!TextUtils.isEmpty(backCCPic)) {
                    cardStatus.setBackCCPic(backCCPic);
                }
                String holdPic = cardStatus.getHoldPic();
                if (!TextUtils.isEmpty(holdPic)) {
                    cardStatus.setHoldPic(holdPic);
                }
                HPLog.d(HPLog.SSX_TAG, "补件信息解密之后数据：" + cardStatus.toString());
                refreshView();
            }
        });
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.btn_upload_cardpic) {
            String message = "";
            frontUri = c_id_front_photo.getPicUri();
            backUri = c_id_back_photo.getPicUri();
            inHandUri = c_person_with_id.getPicUri();
            if (TextUtils.isEmpty(frontUri) || !c_id_front_photo.isLoadSuccess) {
                message = getString(R.string.tv_please_takephoto_front);
            } else if (TextUtils.isEmpty(backUri) || !c_id_back_photo.isLoadSuccess) {
                message = getString(R.string.tv_please_takephoto_back);
            } else if (TextUtils.isEmpty(inHandUri) || !c_person_with_id.isLoadSuccess) {
                message = getString(R.string.tv_please_takephoto_hold);
            }
            if (!TextUtils.isEmpty(message)) {
                // alert use
                this.showAlertDialog(this, getString(R.string.tip), message, true);
                return;
            }
            doUpload();
        }
    }


    private ConfirmPhotoView.UploadClickListener mUploadClickListener = new ConfirmPhotoView.UploadClickListener() {
        @Override
        public void onUploadClickListener(ConfirmPhotoView view) {
            if (AndPermission.hasPermission(IDCardateActivity.this, Manifest.permission.CAMERA)) {
                HPLog.i(HPLog.TAG_RESULT, "---拍照:");
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//            Intent intent = new Intent(IDCardateActivity.this, CameraCardActivity.class);
                mPicUri = CommonUtils.randomUri(CommonUtils.getAccessDir());
                HPLog.i(HPLog.TAG_RESULT, "---mPicUri:" + mPicUri);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mPicUri);
                int requestCode = TAKE_PICTURE;
                if (c_id_front_photo == view) {
                    requestCode = TAKE_PICTURE_FRONT;
                } else if (c_id_back_photo == view) {
                    requestCode = TAKE_PICTURE_BLACK;
                } else if (c_person_with_id == view) {
                    requestCode = TAKE_PICTURE_IN_HAND;
                }
//            intent.putExtra(CameraCardActivity.REQUEST_CODE,requestCode);
                startActivityForResult(intent, requestCode);
            } else {
                AndPermission.with(IDCardateActivity.this).requestCode(REQUEST_CODE_PERMISSION_CAMERA).
                        permission(Manifest.permission.CAMERA).
                        rationale(new RationaleListener() {
                            @Override
                            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                AndPermission.rationaleDialog(IDCardateActivity.this, rationale).show();
                            }
                        }).send();
            }
        }
    };


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Activity.RESULT_OK == resultCode) {
            ConfirmPhotoView photo = null;
            if (TAKE_PICTURE_FRONT == requestCode) {
                photo = c_id_front_photo;
            } else if (TAKE_PICTURE_BLACK == requestCode) {
                photo = c_id_back_photo;
            } else if (TAKE_PICTURE_IN_HAND == requestCode) {
                photo = c_person_with_id;
            }
//            String path = data.getStringExtra(CameraCardActivity.RESULT_PATH);
            if (mPicUri != null) {
//                HPLog.i(HPLog.YL_TAG, "onActivityResult set path:" + path);
//                photo.setPic("file://" + path);
                String uri = mPicUri.toString();
                photo.setPic(uri);
            }
        } else if (requestCode == REQUEST_CODE_PERMISSION_CAMERA) {
            initPermission();
        }
        // 控制程序调用相机的时候，不去发版本检测协议。
//        ZZTConfig.isActive = false;
        mPicUri = null;
    }

    @Override
    protected void onStop() {
        HPLog.i("ssss", "onStop");
        cancelTask();
        super.onStop();
    }

    private void cancelTask() {
        //当该activity不可见的时候，取消上传任务。
        if (null != mTask) {
            HPLog.i("ssss", "cancel task");
            mTask.cancel(true);
            mTask = null;
        }
    }

    private void doUpload() {
        HPLog.i("time", "doUpload:" + SystemClock.elapsedRealtime());
        cancelTask();
        //检测网络，如果网络不可用，提示打开网络
        if (checkNetAndAlert(this)) {
            return;
        }
        //返回值。0表示成功，1表示失败，2，表示用户取消
        mTask = new MyAsyncTask<Void, UploadProtocolConstant.TYPE, Integer>() {
            ProgressDialog progressDialog = null;

            @Override
            protected void onPreExecute() {
                progressDialog = new ProgressDialog(IDCardateActivity.this);
                progressDialog.setMessage(getString(R.string.uploading_template, ""));
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setCancelable(false);
                progressDialog.show();
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Integer result) {
                if (null != progressDialog) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                if (0 == result) {
                    //成功以后，删除图片
                    CommonUtils.removePics();
                    gotoUploadSuccess();
                } else if (1 == result) {
                    //上传失败
                    Toast.makeText(IDCardateActivity.this, R.string.upload_failed, Toast.LENGTH_SHORT).show();
                } else if (2 == result) {
                    //上传取消
                    Toast.makeText(IDCardateActivity.this, R.string.upload_cancel, Toast.LENGTH_LONG).show();
                    HPLog.e("result", "upload canceled");
                }
                super.onPostExecute(result);
            }

            @Override
            protected void onProgressUpdate(UploadProtocolConstant.TYPE... values) {
                if (null != progressDialog) {
                    String picDes = getString(R.string.ID_card_photo);
                    switch (values[0]) {
                        case FRONT: {
                            picDes = getString(R.string.ID_card_photo);
                            break;
                        }
                        case BACK: {
                            picDes = getString(R.string.ID_card_back_photo);
                            break;
                        }
                        case INHAND: {
                            picDes = getString(R.string.ID_person_with_card);
                            break;
                        }
                    }
                    progressDialog.setMessage(getString(R.string.uploaded_id_card, picDes));
                }
                super.onProgressUpdate(values);
            }

            @Override
            protected void onCancelled(Integer result) {
                if (null != progressDialog) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                //上传取消
                Toast.makeText(IDCardateActivity.this, R.string.upload_cancel, Toast.LENGTH_LONG).show();
                super.onCancelled();
            }

            @Override
            protected Integer doInBackground(Void... params) {
                CRC32 mCrc32 = new CRC32();
                //发送正面图片
                if (!mFrontUploaded) {
                    if (uploadPhotoWithJson(frontUri, UploadProtocolConstant.TYPE.FRONT, mCrc32)) {
                        this.publishProgress(UploadProtocolConstant.TYPE.FRONT);
                        mFrontUploaded = true;
                    } else {
                        return 1;
                    }
                }
                if (this.isCancelled()) {
                    return 2;
                }
                //发送反面图片
                if (!mBackUploaded) {
                    if (uploadPhotoWithJson(backUri, UploadProtocolConstant.TYPE.BACK, mCrc32)) {
                        this.publishProgress(UploadProtocolConstant.TYPE.BACK);
                        mBackUploaded = true;
                    } else {
                        return 1;
                    }
                }
                if (this.isCancelled()) {
                    return 2;
                }
                //发送手持图片
                if (!mInHandUploaded) {
                    if (uploadPhotoWithJson(inHandUri, UploadProtocolConstant.TYPE.INHAND, mCrc32)) {
                        this.publishProgress(UploadProtocolConstant.TYPE.INHAND);
                        mInHandUploaded = true;
                    } else {
                        return 1;
                    }
                }
                if (this.isCancelled()) {
                    return 2;
                }
                return 0;
            }
        };
        mTask.execute();
    }

    private void gotoUploadSuccess() {
        Toast.makeText(IDCardateActivity.this, R.string.upload_img_success, Toast.LENGTH_LONG).show();
        //隐藏上传按钮reupload_warning
        btn_upload_cardpic.setEnabled(false);
        reupload_warning.setVisibility(View.GONE);
        ApiNoticeFactory.getInstance().doBroadCastNotice(ApiNoticeListener.NOTICE_ACTION, null);
        btn_upload_cardpic.postDelayed(new Runnable() {
            @Override
            public void run() {
                goBack();
            }
        }, 3000);
    }

    /***
     * 上传图片返回json数据
     * @param uri actionc
     * @param type 上传类型
     * @param crc32 orc32格式
     * @return
     */
    private boolean uploadPhotoWithJson(String uri, UploadProtocolConstant.TYPE type, CRC32 crc32) {
        HPLog.i("result", "upload url:" + uri);
        Hashtable<String, String> p = new Hashtable<String, String>();
        String acc = AccountUtils.getAccountName(this);
        String channel = ClientEngine.CHANNEL;
        int t = type.ordinal();
        String hex = "";
        String imgCheck = "";

        byte[] imgByte = null;
        Bitmap bitmap;
        if (BitmapLoader.isHttpUrl(uri)) {
            HPLog.i("result", "uploadPhoto isHttpUrl(uri)");
            imgByte = BitmapLoader.getInstance(IDCardateActivity.this).loadBitmapNoCompress(uri);
        } else {
            HPLog.i("result", "uploadPhoto isNotHttpUrl(uri)");
            bitmap = BitmapLoader.getInstance(IDCardateActivity.this).loadBitmap(uri, uri);
            imgByte = CommonUtils.getBitmapBytes(bitmap, ZZTConstant.MAXBYTE);
        }

        HPLog.i("result", "  CommonUtils.getBitmapBytes after" + type + " size: " + imgByte.length / 1024);
        imgCheck = CommonUtils.getCRC(crc32, imgByte);
        p.put(UploadProtocolConstant.KEY_CHECK, imgCheck);
        p.put(UploadProtocolConstant.ACCOUNT, SecureManager.getInstance().des(acc, 1, null));
        p.put(UploadProtocolConstant.CHANNEL, channel);
        p.put(UploadProtocolConstant.KEY_PICTYPE, String.valueOf(t));
        ResponseBean resp;
        // 根据后台的情况，采用不同的上传方式。目前采用上传HEX str.
        // 等待后期后台，可以接受二进制上传。再采用上传二进制的方式。二进制上传包会小一倍。
        HPLog.i("result", "ZZTConfig.UPLOAD_BIN:" + ZZTConfig.UPLOAD_BIN);
        if (ZZTConfig.UPLOAD_BIN) {
            // 传二进制数据到后台
            HPLog.i("time", "uploadPhoto: after prepare data" + SystemClock.elapsedRealtime() + " " + type.toString());
            HPLog.i("result", "参数：" + p.toString());
            resp = HttpSFTConnector.uploadPic2ServerWithJson(IDCardateActivity.this, ResponseBean.class, HttpUrlConstant.Do_UpdateMerchantCertInfo, p, imgByte);
            HPLog.i("time", "uploadPhoto: after response data" + SystemClock.elapsedRealtime() + " " + type.toString());
        } else {
            // 传HEX str到后台
            hex = CommonUtils.bytesToHexString(imgByte);
            if (TextUtils.isEmpty(hex)) {
                // outOfMemory 返回上传失败。
                return false;
            }
            p.put(UploadProtocolConstant.KEY_PIC, hex);
            HPLog.i("time", "uploadPhoto: after prepare data" + SystemClock.elapsedRealtime() + " " + type.toString());
            resp = HttpSFTConnector.postData2ServerWithJson(IDCardateActivity.this, ResponseBean.class, HttpUrlConstant.Do_UpdateMerchantCertInfo, p);
            HPLog.i("time", "uploadPhoto: after response data" + SystemClock.elapsedRealtime() + " " + type.toString());
        }
        String responseCode = resp.getResponseCode();
        if (!TextUtils.isEmpty(responseCode) && (responseCode.equals("0") || responseCode.equals("0.0"))) {
            return true;
        } else {
            String errMessage = resp.getErrMessage();
            this.showAlertDialog(this, getString(R.string.tip), errMessage);
            return false;
        }
    }

    /***
     * 上传不见信息 lua数据格式
     * @param uri actionc
     * @param type 上传类型
     * @param crc32 orc32格式
     * @return
     */
    private boolean uploadPhoto(String uri, UploadProtocolConstant.TYPE type, CRC32 crc32) {
        HPLog.i("result", "upload url:" + uri);
        Hashtable<String, String> p = new Hashtable<String, String>();
        String acc = AccountUtils.getAccountName(this);
        String channel = ClientEngine.CHANNEL;
        int t = type.ordinal();
        String hex = "";
        String imgCheck = "";

        byte[] imgByte = null;
        Bitmap bitmap;
        if (BitmapLoader.isHttpUrl(uri)) {
            HPLog.i("result", "uploadPhoto isHttpUrl(uri)");
            imgByte = BitmapLoader.getInstance(IDCardateActivity.this).loadBitmapNoCompress(uri);
        } else {
            HPLog.i("result", "uploadPhoto isNotHttpUrl(uri)");
            bitmap = BitmapLoader.getInstance(IDCardateActivity.this).loadBitmap(uri, uri);
            imgByte = CommonUtils.getBitmapBytes(bitmap, ZZTConstant.MAXBYTE);
        }

        HPLog.i("result", "  CommonUtils.getBitmapBytes after" + type + " size: " + imgByte.length / 1024);
        imgCheck = CommonUtils.getCRC(crc32, imgByte);
        p.put(UploadProtocolConstant.KEY_CHECK, imgCheck);
        p.put(UploadProtocolConstant.ACCOUNT, SecureManager.getInstance().des(acc, 1, null));
        p.put(UploadProtocolConstant.CHANNEL, channel);
        p.put(UploadProtocolConstant.KEY_PICTYPE, String.valueOf(t));
        Hashtable<String, Object> resp;
        // 根据后台的情况，采用不同的上传方式。目前采用上传HEX str.
        // 等待后期后台，可以接受二进制上传。再采用上传二进制的方式。二进制上传包会小一倍。
        HPLog.i("result", "ZZTConfig.UPLOAD_BIN:" + ZZTConfig.UPLOAD_BIN);
        if (ZZTConfig.UPLOAD_BIN) {
            // 传二进制数据到后台
            HPLog.i("time", "uploadPhoto: after prepare data" + SystemClock.elapsedRealtime() + " " + type.toString());
            HPLog.i("result", "参数：" + p.toString());
            resp = HttpSFTConnector.uploadPic2Server(IDCardateActivity.this, HttpUrlConstant.Do_UpdateMerchantCertInfo, p, imgByte);
            HPLog.i("time", "uploadPhoto: after response data" + SystemClock.elapsedRealtime() + " " + type.toString());
        } else {
            // 传HEX str到后台
            hex = CommonUtils.bytesToHexString(imgByte);
            if (TextUtils.isEmpty(hex)) {
                // outOfMemory 返回上传失败。
                return false;
            }
            p.put(UploadProtocolConstant.KEY_PIC, hex);
            HPLog.i("time", "uploadPhoto: after prepare data" + SystemClock.elapsedRealtime() + " " + type.toString());
            resp = HttpSFTConnector.postData2Server(IDCardateActivity.this, HttpUrlConstant.Do_UpdateMerchantCertInfo, p);
            HPLog.i("time", "uploadPhoto: after response data" + SystemClock.elapsedRealtime() + " " + type.toString());
        }
        int respCode = (Integer) resp.get(HttpEngine.Key_RespCode);
        String errMsg = (String) resp.get(HttpEngine.Key_RespErrMsg);
        HPLog.i("result", "respCode:" + respCode + ",errMsg:" + errMsg);
        if (respCode < 0 || !TextUtils.isEmpty(errMsg)) {
            return false;
        }
        byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
        if (data == null) {
            return false;
        }
        LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, false);
        if (luaTable == null) {
            Log.i("result", "luaTable == null");
            return false;
        }
        String responseCode = String.valueOf(luaTable.rawget("responseCode"));
        HPLog.i("result", "responseCode:" + responseCode);
        if (!TextUtils.isEmpty(responseCode) && (responseCode.equals("0") || responseCode.equals("0.0"))) {
            return true;
        } else {
            String em = (String) luaTable.rawget("errMessage");
            HPLog.i("result", "em:" + em);
            this.showAlertDialog(this, getString(R.string.tip), em);
            /*if (!TextUtils.isEmpty(em)) {
                dealWithLoginTimeOut(resp);
            }*/
            return false;
        }
    }

    @Override
    protected void goBack() {
        super.goBack();
    }

    @Override
    public void onSucceed(int requestCode, List<String> grantPermissions) {
        if (requestCode == REQUEST_CODE_PERMISSION_CAMERA) {
            HPLog.d(HPLog.SSX_TAG, grantPermissions.toString());
            Toast.makeText(this, R.string.message_camera_succesed, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取权限
     */
    private void initPermission() {
        if (!AndPermission.hasPermission(this, Manifest.permission.CAMERA)) {
            AndPermission.with(this).requestCode(REQUEST_CODE_PERMISSION_CAMERA).
                    permission(Manifest.permission.CAMERA).
                    rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            AndPermission.rationaleDialog(IDCardateActivity.this, rationale).show();
                        }
                    }).send();
        }
    }

}
